package com.junko.admin.controller;

import com.junko.admin.configuration.MyConfig;
import com.junko.admin.tool.ToolIDEA;
import com.junko.core.base.BaseController;
import com.junko.core.constant.ConstantWebContext;
import com.junko.core.tool.ToolDateTime;
import com.junko.core.tool.ToolWeb;
import com.junko.model.back.Admin;
import com.junko.service.back.IAdminService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class BaseBackendController extends BaseController{
    @Resource
    private IAdminService adminService;
    /**
     * 获取当前管理员
     *
     * @return
     */
    protected Admin getCurrentAdmin(HttpServletResponse response) {
        // 加密串存储位置，默认先取header
        String authmark = request.getHeader(ConstantWebContext.cookie_authmark);

        // 如果为空，再取cookie
        if (StringUtils.isEmpty(authmark)) {
            authmark = ToolWeb.getCookieValueByName(request, ConstantWebContext.cookie_authmark);
        }

        // 登录cookie标识异常
        if (StringUtils.isEmpty(authmark)) {
            ToolWeb.addCookie(request, response, "", null, true, ConstantWebContext.cookie_authmark, null, 0);
            return null;
        }

        // 1.解密认证数据，外层
        String outer = ToolIDEA.decrypt(MyConfig.config_securityKey_idea,authmark);
        if (StringUtils.isEmpty(outer)) {
            ToolWeb.addCookie(request, response, "", null, true, ConstantWebContext.cookie_authmark, null, 0);
            return null;
        }
        String[] outerArr = outer.split(".#.");    // arr[0]：USERID，arr[1]：inner
        String adminId = outerArr[0];
        Admin admin = adminService.selectByPrimaryKey(Integer.valueOf(adminId));
        if (admin == null) {
            return null;
        }
        String secretkey = admin.getIdea();
        String inner = ToolIDEA.decrypt(secretkey, outerArr[1]);

        // 2. 分解认证数据，内层
        String[] innerArr = inner.split(".#.");        // arr[0]：scheme，arr[1]：时间戳，arr[2]：USER_IP， arr[3]：USER_AGENT， arr[4]：autoLogin
        String scheme = innerArr[0];                            // scheme
        long loginDateTimes = Long.parseLong(innerArr[1]);        // 时间戳
        String ips = innerArr[2];                                // ip地址
        String userAgent = innerArr[3];                        // USER_AGENT
        boolean autoLogin = Boolean.valueOf(innerArr[4]);        // 是否自动登录

        // 3.用户当前数据
        String newScheme = request.getScheme();
        String newIp = ToolWeb.getIpAddr(request);
        String newUserAgent = request.getHeader("User-Agent");

        Date start = ToolDateTime.getDate();
        start.setTime(loginDateTimes); // 用户自动登录开始时间
        int day = ToolDateTime.getDateDaySpace(start, ToolDateTime.getDate()); // 已经登录多少天
        int maxAge = MyConfig.config_cookie_maxAge;    // cookie自动登录有效天数

        // 4. 验证数据有效性
        if (scheme.equals(newScheme)
                && ips.equals(newIp)
                && (userAgent.equals(newUserAgent))
                && day <= maxAge) {
            // 如果非记住密码（非自动登录），单次登陆有效时间验证
            if (!autoLogin) {
                int minute = ToolDateTime.getDateMinuteSpace(start, new Date());
                int session = MyConfig.config_session_timeout;
                if (minute > session) {
                    return null;
                } else {
                    // 重写登录标识cookie
                    setCurrentAdmin(response, admin, autoLogin);
                }
            }
            // 返回用户数据
            return adminService.selectByPrimaryKey(Long.valueOf(adminId));
        }
        return null;
    }

    /**
     * 设置当前管理员
     *
     * @param response
     * @param admin
     * @param autoLogin
     */
    protected void setCurrentAdmin(HttpServletResponse response, Admin admin, Boolean autoLogin) {
        // 1.设置cookie有效时间
        // 2.设置用户名到cookie
        ToolWeb.addCookie(request, response, "", null, true, "account", admin.getAccount(), MyConfig.config_cookie_maxAge);
        // 3.生成登陆认证cookie
        String secretkey = admin.getIdea();
        Integer adminId = admin.getId();
        String scheme = request.getScheme();
        String ip = ToolWeb.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        long date = ToolDateTime.getDateByTime();

        // 内层用户私有密钥加密
        String inner = new StringBuilder(scheme) // scheme.#.时间戳.#.USER_IP.#.USER_AGENT.#.autoLogin
                .append(".#.").append(date)
                .append(".#.").append(ip)
                .append(".#.").append(userAgent)
                .append(".#.").append(autoLogin)
                .toString();
        inner = ToolIDEA.encrypt(secretkey, inner);

        // 外层使用系统公共密钥加密
        String outer = new StringBuilder(adminId + "") // userIds.#.inner
                .append(".#.").append(inner)
                .toString();
        outer = ToolIDEA.encrypt(MyConfig.config_securityKey_idea,outer);

        // 4. 添加到Cookie和header
        ToolWeb.addCookie(request, response, "", null, true, ConstantWebContext.cookie_authmark, outer, MyConfig.config_cookie_maxAge);
        response.setHeader(ConstantWebContext.cookie_authmark, outer);
    }

    /**
     * 获取当前管理员id
     *
     * @param response
     * @return
     */
    protected Integer getCurrentAdminId(HttpServletResponse response) {
        Admin admin = getCurrentAdmin(response);
        return admin == null ? null : admin.getId();
    }
}
